import React,{useEffect, useState} from 'react'
import { Search} from 'react-vant'
import { Delete } from '@react-vant/icons';
import {useNavigate} from 'react-router-dom'


export default function Searchs() {
  const [value, setValue] = useState(''); 
  const navigate = useNavigate();
  const [data, setData] = useState([]);
  useEffect(()=>{
    const searchHistory = localStorage.getItem('searchHistory')
    if (searchHistory) {
      setData(JSON.parse(searchHistory)); // 将搜索历史字符串解析为数组
    }
  },[])

  //搜索
  const handleSearch = () => {
    // 获取之前的搜索历史
    const searchHistory = localStorage.getItem('searchHistory');
    let updatedData = [];

    if (searchHistory) {
      updatedData = JSON.parse(searchHistory); // 解析搜索历史字符串为数组
    }

    updatedData.push(value); // 添加当前搜索关键字
    if (updatedData.length > 6) {
      updatedData = updatedData.slice(updatedData.length - 6, updatedData.length);
    }
    localStorage.setItem('searchHistory', JSON.stringify(updatedData)); // 保存更新后的搜索历史

    navigate('/home/clothes/65237423265d388e329e6777', { state: { value } });
  };
  const handerClaer = () =>{
    localStorage.removeItem('searchHistory')
    setData([])
  }
  return (
    <div>
     <Search value={value} onChange={setValue} placeholder="请输入搜索关键词"   onSearch={handleSearch}/>
     <Delete  onClick={()=>handerClaer()}/>
     <ul>
      {data.map((item,index)=>{
        return (
          <li key={index}>{item}</li>
        )
      })}
     </ul>
    </div>
  )
}
